import * as vscode from 'vscode';
import { DeepseekAPI } from './deepseekAPI';
import { getLanguageConfig } from './languageSupport';

export interface CodeLens {
    range: vscode.Range;
    command: vscode.Command;
}

export class LanguageFeatureProvider {
    private deepseekAPI: DeepseekAPI;

    constructor(deepseekAPI: DeepseekAPI) {
        this.deepseekAPI = deepseekAPI;
    }

    // 提供代码诊断信息
    public async provideDiagnostics(document: vscode.TextDocument): Promise<vscode.Diagnostic[]> {
        const code = document.getText();
        const langConfig = getLanguageConfig(document.languageId);
        if (!langConfig) return [];

        try {
            const analysis = await this.deepseekAPI.analyzeCode(code);
            const diagnostics: vscode.Diagnostic[] = [];

            for (const refactoring of analysis.refactorings) {
                for (const change of refactoring.changes) {
                    for (const edit of change.edits) {
                        const range = new vscode.Range(
                            document.positionAt(edit.start),
                            document.positionAt(edit.end)
                        );

                        const severity = this.getDiagnosticSeverity(refactoring.priority);
                        const diagnostic = new vscode.Diagnostic(
                            range,
                            `${refactoring.title}: ${edit.explanation}`,
                            severity
                        );
                        diagnostic.source = 'DeepSeek';
                        diagnostic.code = refactoring.type;
                        diagnostics.push(diagnostic);
                    }
                }
            }

            return diagnostics;
        } catch (error) {
            console.error('Error providing diagnostics:', error);
            return [];
        }
    }

    // 提供代码操作（快速修复）
    public async provideCodeActions(
        document: vscode.TextDocument,
        range: vscode.Range,
        context: vscode.CodeActionContext
    ): Promise<vscode.CodeAction[]> {
        const actions: vscode.CodeAction[] = [];

        for (const diagnostic of context.diagnostics) {
            if (diagnostic.source !== 'DeepSeek') continue;

            const action = new vscode.CodeAction(
                `Fix: ${diagnostic.message}`,
                vscode.CodeActionKind.QuickFix
            );
            
            // 获取修复建议
            const fix = await this.deepseekAPI.getSuggestionFix(
                document.getText(),
                document.offsetAt(diagnostic.range.start),
                document.offsetAt(diagnostic.range.end)
            );

            if (fix) {
                const edit = new vscode.WorkspaceEdit();
                edit.replace(document.uri, diagnostic.range, fix.newText);
                action.edit = edit;
                action.diagnostics = [diagnostic];
                actions.push(action);
            }
        }

        return actions;
    }

    // 提供代码镜头（CodeLens）
    public async provideCodeLenses(document: vscode.TextDocument): Promise<vscode.CodeLens[]> {
        const code = document.getText();
        const langConfig = getLanguageConfig(document.languageId);
        if (!langConfig) return [];

        try {
            const analysis = await this.deepseekAPI.analyzeCode(code);
            const lenses: vscode.CodeLens[] = [];

            for (const refactoring of analysis.refactorings) {
                if (refactoring.priority === 'high') {
                    for (const change of refactoring.changes) {
                        const range = new vscode.Range(
                            document.positionAt(change.edits[0].start),
                            document.positionAt(change.edits[0].end)
                        );

                        lenses.push(new vscode.CodeLens(range, {
                            title: `💡 ${refactoring.title}`,
                            command: 'deepseek.applyRefactoring',
                            arguments: [document, refactoring]
                        }));
                    }
                }
            }

            return lenses;
        } catch (error) {
            console.error('Error providing code lenses:', error);
            return [];
        }
    }

    private getDiagnosticSeverity(priority: string): vscode.DiagnosticSeverity {
        switch (priority.toLowerCase()) {
            case 'high':
                return vscode.DiagnosticSeverity.Error;
            case 'medium':
                return vscode.DiagnosticSeverity.Warning;
            case 'low':
                return vscode.DiagnosticSeverity.Information;
            default:
                return vscode.DiagnosticSeverity.Hint;
        }
    }
} 